<?php

namespace App\Models;

use App\Enums\Notification\CounterApply;
use App\Enums\Notification\CounterNotify;
use App\Enums\Notification\GameNotify;
use App\Enums\Notification\NotificationEnumInterface;
use App\Enums\Notification\ReserveNotify;
use App\NotificationActions\NotificationActionInterface;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class StoreNotification extends Model
{
    use HasFactory;

    protected $fillable = [
        'store_id', 'type', 'notification_name', 'model_id', 'is_actioned', 'is_agree', 'need_action', 'operator_user_id',
    ];

    protected $casts = [
        'is_actioned' => 'boolean',
        'need_action' => 'boolean',
        'is_agree' => 'boolean'
    ];

    public function operator()
    {
        return $this->belongsTo(User::class, 'operator_user_id');
    }

    public function store()
    {
        return $this->belongsTo(Store::class);
    }

    public function getModel()
    {
        $action = $this->getAction();
        return $action->getModel($this->model_id);
    }

    public function getTypeEnum() : NotificationEnumInterface|null
    {
        switch ($this->type) {
            case 'counter_apply':
                return CounterApply::from($this->notification_name);
            case 'counter_notify':
                return CounterNotify::from($this->notification_name);
            case 'game_notify':
                return GameNotify::from($this->notification_name);
            case 'reserve_notify':
                return ReserveNotify::from($this->notification_name);
            default:
                return null;
        }
    }

    public function getAction() : NotificationActionInterface|null
    {
        $enum = $this->getTypeEnum();

        return $enum->action();
    }

    /**
     * 同意操作
     */
    public function agree()
    {
        if (!$this->need_action)
            return ;

        DB::transaction(function () {

            $action = $this->getAction();

            if (!empty($action)) {
                $action->action($this->model_id);
                $this->is_actioned = true;
            }

            $this->is_agree = true;
            $this->save();
        });
    }

    /**
     * 拒绝操作
     */
    public function refuse()
    {
        if (!$this->need_action)
            return ;

        $this->is_agree = false;
        $this->save();
    }
}
